//
//  DocumentViewController.m
//  WebView加载文件
//
//  Created by xiacl on 2018/9/6.
//  Copyright © 2018年 a2345. All rights reserved.
//

#import "DocumentViewController.h"
#import <objc/runtime.h>
@interface DocumentViewController ()<QLPreviewControllerDataSource, UIDocumentInteractionControllerDelegate, QLPreviewControllerDelegate>

/**
 <#Description#>
 */
@property (strong, nonatomic) UIDocumentInteractionController *documentController;

/**
 <#Description#>
 */
@property (assign, nonatomic) BOOL canShowToolbar;

@end

@implementation DocumentViewController

- (instancetype)init {
    if ([super init]) {
        _canShowToolbar = NO;
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
//    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor greenColor];
    self.dataSource = self;
//    self.delegate = self;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"hehe" style:UIBarButtonItemStyleDone target:self action:@selector(right)];
    
    [self addObserver:self forKeyPath:@"currentPreviewItemIndex" options:NSKeyValueObservingOptionNew context:nil];
    
//    [self addObserver:self forKeyPath:@"canShowToolbar" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)showAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
                                  
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (self.pathURL.count == 1) {
            [self.navigationController popViewControllerAnimated:YES];
        }
    }];
    
    UIAlertAction *defualt = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
       
        UIDocumentInteractionController *documentVC = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:self.pathURL.firstObject]];
        documentVC.delegate = self;
//        [documentVC presentOpenInMenuFromRect:self.view.bounds inView:self.view animated:YES];
        
        
        [documentVC presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
        
//        UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"xixi" style:UIBarButtonItemStylePlain target:self action:@selector(xixi)];
        
//        [documentVC presentOpenInMenuFromBarButtonItem:item animated:YES];
        self.documentController = documentVC;
    }];
    
    [alertVC addAction:cancel];
    [alertVC addAction:defualt];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)right {
    NSLog(@"%s", __func__);
}

- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return self.pathURL.count;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    NSURL *url = [NSURL fileURLWithPath:self.pathURL[index]];
    return url;
}


- (void)previewControllerWillDismiss:(QLPreviewController *)controller {
     NSLog(@"%s", __func__);
}

- (void)previewControllerDidDismiss:(QLPreviewController *)controller {
     NSLog(@"%s", __func__);
}

- (BOOL)previewController:(QLPreviewController *)controller shouldOpenURL:(NSURL *)url forPreviewItem:(id <QLPreviewItem>)item {
    NSLog(@"%s", __func__);
    return YES;
}

- (CGRect)previewController:(QLPreviewController *)controller frameForPreviewItem:(id <QLPreviewItem>)item inSourceView:(UIView * _Nullable * __nonnull)view {
    NSLog(@"%s", __func__);
    return self.view.bounds;
}

- (UIImage *)previewController:(QLPreviewController *)controller transitionImageForPreviewItem:(id <QLPreviewItem>)item contentRect:(CGRect *)contentRect {
     NSLog(@"%s", __func__);
    return nil;
}

- (UIView* _Nullable)previewController:(QLPreviewController *)controller transitionViewForPreviewItem:(id <QLPreviewItem>)item NS_AVAILABLE_IOS(10_0) {
    NSLog(@"%s", __func__);
    return nil;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"currentPreviewItemIndex"]) {
        NSURL *fileUrl = [NSURL fileURLWithPath:self.pathURL[self.currentPreviewItemIndex]];
        
        NSString *title = [fileUrl.lastPathComponent stringByDeletingPathExtension];
        self.navigationItem.title = title;
        if (![self.class canPreviewItem:fileUrl]) {
            [self showAlert:@"提示" message:[title stringByAppendingString:@"暂不支持浏览,请使用其他方式浏览"]];
        }
        
       
        
        if ([keyPath isEqualToString:@"canShowToolbar"]) {
            NSNumber *nub = change[NSKeyValueChangeNewKey];
            if (_canShowToolbar != NO) {
               _canShowToolbar = NO;
            }
        }
        
//        self.navigationItem.title =
//        NSLog(@"%d", self.currentPreviewItemIndex);
    }
    
}
//返回当前类的所有属性
- (NSMutableArray *)getProperties:(Class)cls { // 获取当前类的所有属性
    unsigned int count;
    // 记录属性个数
    objc_property_t *properties = class_copyPropertyList(cls, &count);
    // 遍历
    NSMutableArray *mArray = [NSMutableArray array]; for (int i = 0; i < count; i++) {
        // An opaque type that represents an Objective-C declared property.
        // objc_property_t 属性类型
        objc_property_t property = properties[i];
        // 获取属性的名称 C语言字符串
        const char *cName = property_getName(property);
        // 转换为Objective C 字符串
        NSString *name = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding];
        [mArray addObject:name];
    } return mArray.copy;
}

//- (BOOL)canShowToolbar {
//    return NO;
//}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
